﻿using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Specialized;
using System.IO;

namespace MyConfigFile
{
    /// <summary>
    /// Create a New INI file to store or load data
    /// </summary>
    public static class SimpleConfigFile
    {
        /// <summary>
        /// 读取简单的配置文件,只有若干简单的name和value对
        /// 配置文件格式:
        /// name_startwith[name]name_endwith
        /// [value]
        /// 例如：
        /// --> [@@my_name@@]my_value  
        /// --> name_startwith='[@@' name_endwith='@@]' name='my_name' value='my_value'
        /// </summary>
        /// <param name="filepath">配置文件路径</param>
        /// <param name="name_startwith">name开始标识</param>
        /// <param name="name_endwith">name结束标识</param>
        /// <returns>所有name value串</returns>
        public static NameValueCollection GetAllConfigs(string filepath,string name_startwith, string name_endwith)
        {
            NameValueCollection nvc = new NameValueCollection();

            string content = File.ReadAllText(filepath);
            int i = 0, j = 0, k = 0;

            while (k < content.Length)
            {
                i = content.IndexOf(name_startwith, j);
                if (i >= 0)
                    j = content.IndexOf(name_endwith, i + name_startwith.Length);
                else
                    break;

                if (j > 0)
                    k = content.IndexOf(name_startwith, j + name_endwith.Length);
                else
                    break ;

                if (k < 0)
                    k = content.Length;

                nvc.Add(content.Substring(i + name_startwith.Length, j - i - name_startwith.Length),
                            content.Substring(j + name_endwith.Length, k - j - name_endwith.Length));
            }

            return nvc;
        }
    }
}